package com.hzcx.app.simplechat.ui.setting;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.hyphenate.chat.EMImageMessageBody;
import com.hyphenate.chat.EMMessage;
import com.hzcx.app.simplechat.R;
import com.hzcx.app.simplechat.base.BaseActivity;
import com.hzcx.app.simplechat.chat.ChatUi;
import com.hzcx.app.simplechat.chat.ChatUiHelper;
import com.hzcx.app.simplechat.chat.ChatUtil;
import com.hzcx.app.simplechat.chat.adapter.ChatBottomMenuAdapter;
import com.hzcx.app.simplechat.chat.bean.ChatMoreMenuBean;
import com.hzcx.app.simplechat.chat.constant.ChatConstant;
import com.hzcx.app.simplechat.chat.ui.ChatMessageListView;
import com.hzcx.app.simplechat.chat.ui.RecordButton;
import com.hzcx.app.simplechat.ui.chat.ChatQuickMsgAddActivity;
import com.hzcx.app.simplechat.ui.chat.ChatQuickMsgManagerActivity;
import com.hzcx.app.simplechat.ui.chat.adapter.ChatQuickMsgAdapter;
import com.hzcx.app.simplechat.ui.chat.bean.ChatQuickMsgBean;
import com.hzcx.app.simplechat.ui.chat.event.ChatQuickMsgRefreshEvent;
import com.hzcx.app.simplechat.ui.setting.bean.GroupMessageListBean;
import com.hzcx.app.simplechat.ui.setting.contract.GroupMessageSendContract;
import com.hzcx.app.simplechat.ui.setting.event.GroupMessageEvent;
import com.hzcx.app.simplechat.ui.setting.presenter.GroupMessageSendPresenter;
import com.hzcx.app.simplechat.util.UserInfoUtil;
import com.hzcx.app.simplechat.util.empty.EmptyUtils;
import com.hzcx.app.simplechat.util.photo.PhotoUtil;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.listener.OnResultCallbackListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 群发信息界面
 */
public class GroupMessageSendActivity extends BaseActivity<GroupMessageSendPresenter> implements BaseQuickAdapter.OnItemClickListener, ChatUiHelper.OnChatUiHelperListener,
        OnResultCallbackListener<LocalMedia>, GroupMessageSendContract.View {

    public static final String INTENT_RESEND = "INTENT_RESEND";
    public static final String INTENT_COUNT = "INTENT_COUNT";
    public static final String INTENT_NAMES = "INTENT_NAMES";
    public static final String INTENT_HXUSERNAME = "INTENT_HXUSERNAME";
    public static final String INTENT_IDS = "INTENT_IDS";

    @BindView(R.id.include_emoji)
    LinearLayout includeEmoji;
    @BindView(R.id.include_menu)
    LinearLayout includeMenu;
    @BindView(R.id.include_quick_msg)
    LinearLayout includeQuickMsg;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.iv_title_right)
    ImageView ivTitleRight;
    @BindView(R.id.tv_title_right)
    TextView tvTitleRight;
    @BindView(R.id.chat_msg_listview)
    ChatMessageListView chatMsgListview;
    @BindView(R.id.iv_voice)
    ImageView ivVoice;
    @BindView(R.id.iv_keyword)
    ImageView ivKeyword;
    @BindView(R.id.tv_voice)
    RecordButton tvVoice;
    @BindView(R.id.et_content)
    EditText etContent;
    @BindView(R.id.iv_emoji)
    ImageView ivEmoji;
    @BindView(R.id.iv_more)
    ImageView ivMore;
    @BindView(R.id.tv_send)
    TextView tvSend;
    @BindView(R.id.main_layout)
    LinearLayout mainLayout;
    @BindView(R.id.rv_emoji_default)
    RecyclerView rvEmojiDefault;
    @BindView(R.id.rv_emoji_like)
    RecyclerView rvEmojiLike;
    @BindView(R.id.iv_emoji_default)
    ImageView ivEmojiDefault;
    @BindView(R.id.iv_emoji_like)
    ImageView ivEmojiLike;
    @BindView(R.id.home_emoji)
    LinearLayout homeEmoji;
    @BindView(R.id.rv_menu)
    RecyclerView rvMenu;
    @BindView(R.id.bottom_layout)
    RelativeLayout bottomLayout;
    @BindView(R.id.tv_send_num)
    TextView tvSendNum;
    @BindView(R.id.tv_send_nick_name)
    TextView tvSendNickName;
    @BindView(R.id.rv_quick_msg)
    RecyclerView rvQuickMsg;
    @BindView(R.id.ll_quick_msg_null)
    LinearLayout llQuickMsgNull;
    @BindView(R.id.rl_quick_msg_add)
    RelativeLayout rlQuickMsgAdd;
    @BindView(R.id.rl_quick_msg_manager)
    RelativeLayout rlQuickMsgManager;

    private List<ChatMoreMenuBean> menuList;
    private ChatBottomMenuAdapter menuAdapter;

    private ChatUiHelper mUiHelper;

    private GroupMessageListBean reSendBean;

    private String imgPath;
    private String voicePath;
    private int audio_time;
    private String hxUsernames;
    private String ids;

    private List<ChatQuickMsgBean> quickMsgData; // 快捷回复列表
    private ChatQuickMsgAdapter quickMsgAdapter;

    @Override
    public int getLayout() {
        return R.layout.activity_group_message_send;
    }

    @Override
    public void initPresenter() {
        mPresenter = new GroupMessageSendPresenter();
    }

    @Override
    public void initView() {
        tvTitle.setText("群发信息");
    }

    @Override
    public void initData() {
        ids = getIntent().getStringExtra(INTENT_IDS);
        hxUsernames = getIntent().getStringExtra(INTENT_HXUSERNAME);
        reSendBean = (GroupMessageListBean) getIntent().getSerializableExtra(INTENT_RESEND);
        if (reSendBean != null) {
            tvSendNum.setText("您将发送给" + reSendBean.getMember_count() + "位朋友");
            tvSendNickName.setText(reSendBean.getChat_member_ids());
        } else {
            tvSendNum.setText("您将发送给" + getIntent().getIntExtra(INTENT_COUNT, 0) + "位朋友");
            tvSendNickName.setText(getIntent().getStringExtra(INTENT_NAMES));
        }

        initMenu();
        initChatUi();

        // 获取快捷回复列表
        mPresenter.getChatQuickMsgList(this);
    }

    @OnClick({R.id.tv_send, R.id.rl_quick_msg_add, R.id.rl_quick_msg_manager})
    public void viewOnClick(View view) {
        switch (view.getId()) {
            case R.id.tv_send:
                if (reSendBean != null) {
                    mPresenter.reSendMessage(this, reSendBean.getId(), 1, etContent.getText().toString(), audio_time);
                } else {
                    mPresenter.sendMessage(this, ids, hxUsernames, 1, etContent.getText().toString(), audio_time);
                }
                break;
            case R.id.rl_quick_msg_add: // 添加快捷回复
                startActivity(new Intent(this, ChatQuickMsgAddActivity.class));
                break;

            case R.id.rl_quick_msg_manager: // 管理快捷回复
                startActivity(new Intent(this, ChatQuickMsgManagerActivity.class));
                break;
        }
    }


    /**
     * 添加消息
     *
     * @param type
     * @param content
     * @param imgPath
     * @param voicePath
     */
    private void addMessageView(int type, String content, String imgPath, String voicePath, int length) {
        EMMessage message = null;
        if (type == 1) {
            message = EMMessage.createTxtSendMessage(content, "");
            etContent.setText("");
        } else if (type == 3) {
            Uri uri = Uri.parse(imgPath);
            message = EMMessage.createImageSendMessage(uri, false, "");
            EMImageMessageBody imgBody = new EMImageMessageBody(uri);
            imgBody.setRemoteUrl(imgPath);
            message.addBody(imgBody);
        } else if (type == 2) {
            message = EMMessage.createVoiceSendMessage(Uri.parse(voicePath), length, "");
        }
        if (message == null) {
            return;
        }
        message.setAttribute(ChatConstant.EXTRA_SEND_USER_ID, UserInfoUtil.getUserId());
        message.setDirection(EMMessage.Direct.SEND);
        message.setStatus(EMMessage.Status.SUCCESS);
        chatMsgListview.add(message);
    }

    /**
     * 初始化菜单信息
     */
    private void initMenu() {
        menuList = new ArrayList<>();
        menuList.addAll(ChatUi.getInstance().initMenu(false));
        menuAdapter = new ChatBottomMenuAdapter(R.layout.rv_item_chat_bottom_menu, menuList);
        rvMenu.setLayoutManager(new GridLayoutManager(this, 4));
        rvMenu.setAdapter(menuAdapter);

        menuAdapter.setOnItemClickListener(this);
    }

    private void initChatUi() {

        quickMsgData = new ArrayList<>();
        quickMsgAdapter = new ChatQuickMsgAdapter(quickMsgData);
        rvQuickMsg.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
        rvQuickMsg.setAdapter(quickMsgAdapter);
        //mBtnAudio
        mUiHelper = ChatUiHelper.with(this);
        mUiHelper.bindContentLayout(mainLayout)
                .bindttToSendButton(tvSend)
                .bindEditText(etContent)
                .bindBottomLayout(bottomLayout)
                .bindEmojiLayout(includeEmoji)
                .bindAddLayout(includeMenu)
                .bindToAddButton(ivMore)
                .bindToEmojiButton(ivEmoji)
                .bindAudioBtn(tvVoice)
                .bindAudioIv(ivVoice)
                .bindQuickMsgView(includeQuickMsg)
                .bindEmojiData()
                .setOnChatUiHelperListener(this);

        //点击空白区域关闭键盘
        chatMsgListview.getRvMsg().setOnTouchListener((view, motionEvent) -> {
            mUiHelper.hideBottomLayout(false);
            mUiHelper.hideSoftInput();
            etContent.clearFocus();
            ivEmoji.setImageResource(R.mipmap.ic_icon_chat_emoji);
            return false;
        });
        // 发送语音消息
        tvVoice.setOnFinishedRecordListener((audioPath, time) -> {
            File file = new File(audioPath);
            if (file.exists()) {
                voicePath = audioPath;
                audio_time = time;
                mPresenter.upLoadFile(GroupMessageSendActivity.this, voicePath);
            }
        });


        quickMsgAdapter.setOnItemClickListener((adapter, view, position) ->
                mPresenter.sendMessage(GroupMessageSendActivity.this, ids, hxUsernames, 1, quickMsgData.get(position).getMaincontent(), audio_time));
    }

    /**
     * 菜单选择
     *
     * @param adapter
     * @param view
     * @param position
     */
    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        switch (menuList.get(position).getTag()) {
            case ChatMoreMenuBean.TAG_PHOTO: // 相册
                PhotoUtil.showPhoto(this, PictureMimeType.ofImage(), PictureConfig.SINGLE, false, false, null, this);
                break;

            case ChatMoreMenuBean.TAG_CAMERA: // 拍照
                PhotoUtil.showCamera(this, PictureMimeType.ofImage(), PictureConfig.SINGLE, false, false, null, this);
                break;

            case ChatMoreMenuBean.TAG_QUICK_MSG: // 快捷回复
                mUiHelper.showQuickMsgView();
                break;
        }
    }

    @Override
    public void sendEmoji(String path) {

    }

    /**
     * 拍照或选取照片返回
     *
     * @param result
     */
    @Override
    public void onResult(List<LocalMedia> result) {
        for (LocalMedia media : result) {
            if (PictureMimeType.getMimeType(media.getMimeType()) == PictureConfig.TYPE_VIDEO) {

            } else {
                imgPath = PhotoUtil.getPath(result.get(0));
                mPresenter.upLoadImg(this, imgPath);
            }
        }
    }

    @Override
    public void onCancel() {

    }

    /**
     * 群发成功
     *
     * @param type
     */
    @Override
    public void sendSuccess(int type,String content) {
        EventBus.getDefault().post(new GroupMessageEvent());
        addMessageView(type, content, imgPath, voicePath, audio_time);
    }

    /**
     * 图片上传成功
     *
     * @param url
     */
    @Override
    public void imgLoadSuccess(String url) {
        if (reSendBean != null) {
            mPresenter.reSendMessage(this, reSendBean.getId(), 3, url, audio_time);
        } else {
            mPresenter.sendMessage(this, ids, hxUsernames, 3, url, audio_time);
        }
    }

    /**
     * 文件上传成功
     *
     * @param url
     */
    @Override
    public void fileLoadSuccess(String url) {
        if (reSendBean != null) {
            mPresenter.reSendMessage(this, reSendBean.getId(), 2, url, audio_time);
        } else {
            mPresenter.sendMessage(this, ids, hxUsernames, 2, url, audio_time);
        }
    }

    /**
     * 快捷回复列表获取成功
     *
     * @param data
     */
    @Override
    public void qucikMsgResult(List<ChatQuickMsgBean> data) {
        try {
            quickMsgData.clear();
            quickMsgData.addAll(data);
            quickMsgAdapter.notifyDataSetChanged();
            if (quickMsgData.size() > 0) {
                llQuickMsgNull.setVisibility(View.GONE);
            } else {
                llQuickMsgNull.setVisibility(View.VISIBLE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 刷新快捷回复列表
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshQuickMsg(ChatQuickMsgRefreshEvent event) {
        if (event.getTag() == 0 || event.getTag() == 3) {
            mPresenter.getChatQuickMsgList(this);
        } else if (event.getTag() == 1) {
            quickMsgData.remove(event.getPos());
            quickMsgAdapter.notifyDataSetChanged();
        }
    }
}
